package com.oocl.multiple_threads_download.runnable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import com.oocl.multiple_threads_download.pojo.DownloadParams;
import com.oocl.multiple_threads_download.util.FileUtils;

public class DownloadRunnable implements Runnable{

	File file;
	File targetFile;
	long fromIndex;
	long toIndex;
	long curPoint;
	DownloadParams downloadParams;
	
	
	


	public DownloadRunnable(DownloadParams downloadParams, long fromIndex, long toIndex) {
		super();
		this.downloadParams = downloadParams;
		this.file = new File(downloadParams.getTargetFilePath());
		FileUtils.createFile(this.downloadParams.getDownloadPath());
		this.targetFile = new File(this.downloadParams.getDownloadPath());
		this.fromIndex = fromIndex;
		this.toIndex = toIndex;
		this.curPoint = this.fromIndex;
	}

	public void run() {
		if(file.length()<this.fromIndex)
			return;
		
		///下载文件
		try {
			
			InputStream fis = new FileInputStream(file);
//			OutputStream fos = new FileOutputStream(file);
			byte[] buf = new byte[this.downloadParams.getBufLen()];
			long i = 0;
			fis.skip(fromIndex);
			RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
			raf.seek(this.fromIndex);
			while((i = fis.read(buf))!=-1) {
				if(this.curPoint + i >= this.toIndex) {
					raf.write(buf, 0, (int) (this.toIndex - this.curPoint));
					this.curPoint = this.toIndex;
				}else {
					raf.write(buf, 0, (int) i);
					this.curPoint += i;
				}
			}
//			fos.close();
			raf.close();
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
